package com.ssms.controller;

import com.ssms.commons.Result;
import com.ssms.model.SysUser;
import com.ssms.service.SysUserService;
import com.ssms.service.SystemService;
import com.ssms.util.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

@RequestMapping("sys")
@Controller
public class SystemController {

    @Resource
    private SystemService systemService;
    @Resource
    private SysUserService sysUserService;

    @RequestMapping("login")
    @ResponseBody
    public Result login(SysUser sysUser, HttpSession session) {
        return systemService.login(sysUser,session);
    }

    @RequestMapping("welcome")
    public String welcome() {
        return "welcome";
    }

    @RequestMapping("userInfo")
    public String userInfo() {
        return "userInfo";
    }

    @RequestMapping("main")
    public String main() {
        return "main";
    }

    @RequestMapping("logout")
    public void logout(HttpSession session, HttpServletResponse response) throws IOException {
        session.removeAttribute("user");
        response.sendRedirect("/ssms");
        // 此处不能return "redirect:/ssms", 因为控制器中并不存在/ssms路径会报错，/ssms是在WebConfig中添加的映射路径
    }

    @RequestMapping("update")
    @ResponseBody
    public Result update(SysUser sysUser, HttpSession session) {
        Result result = sysUserService.update(sysUser);
        if(result.getCode() == 200){
            SysUser user = (SysUser) session.getAttribute("sysUser");
            String username = sysUser.getUsername();
            if(username != null){
                user.setUsername(username);
            }
            String phone = sysUser.getPhone();
            if(phone != null){
                user.setPhone(phone);
            }
            String sex = sysUser.getSex();
            if(sex != null){
                user.setSex(sex);
            }
            session.setAttribute("sysUser",user);
        }
        return result;
    }

    @RequestMapping("download/scoreTemplet")
    public void scoreTemplet(HttpServletResponse response) throws IOException {
        String filename = "score.xlsx";
        InputStream instream = getClass().getClassLoader().getResourceAsStream("static/" + filename);
        FileUtils.download(instream, response, filename);

    }

    @RequestMapping("download/stuTemplet")
    public void stuTemplet(HttpServletResponse response) throws IOException {
        String filename = "stu.xlsx";
        InputStream instream = getClass().getClassLoader().getResourceAsStream("static/" + filename);
        FileUtils.download(instream, response, filename);
    }
}
